import {
  Controller,
  Get,
  Headers,
  Query,
  UseInterceptors,
  ClassSerializerInterceptor,
  Param,
  Post,
  Body,
  Delete,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { ILike } from 'typeorm';
import { IsAuth } from 'src/decorators/auth.decorator';
import { IResponseData, responseData } from 'src/utils/result';
import { CreateLogDto, FindLogListDto, LogDto } from './log.dto';
import { LogService } from './log.service';

@ApiTags('日志模块')
@ApiBearerAuth()
@Controller('log')
export class LogController {
  constructor(private readonly logService: LogService) {}
  @ApiOperation({ summary: '查询日志列表' })
  @ApiResponse({
    status: 200,
    description: '查询日志列表',
    type: LogDto,
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @Get()
  @IsAuth('system:log:list')
  async findList(
    @Query() dto: FindLogListDto,
    @Headers() headers,
  ): Promise<IResponseData> {
    const res = await this.logService.getLists({
      where: {
        ...dto,
        operator: dto.operator ? ILike('%' + dto.operator + '%') : null,
      },
      order: {
        id: 'DESC',
      },
    });
    return responseData({ data: res, language: headers['language'] });
  }

  @ApiOperation({ summary: '查询日志详情' })
  @ApiResponse({
    status: 200,
    description: '查询日志详情',
    type: LogDto,
  })
  @UseInterceptors(ClassSerializerInterceptor)
  @Get(':id')
  @IsAuth('system:log:detail')
  async find(
    @Param('id') id: number,
    @Headers() headers,
  ): Promise<IResponseData> {
    const res = await this.logService.getOne({
      where: {
        id,
      },
    });
    return responseData({
      code: 100010,
      data: res,
      language: headers['language'],
    });
  }

  @Post()
  @IsAuth('system:log:add')
  @ApiOperation({ summary: '创建日志' })
  @ApiResponse({ status: 200, description: '操作成功' })
  async create(
    @Body() dto: CreateLogDto,
    @Headers() headers,
  ): Promise<IResponseData> {
    const res = await this.logService.createOrUpdate(dto);
    return responseData({
      code: 100020,
      data: res,
      language: headers['language'],
    });
  }

  @Delete()
  @IsAuth('system:log:delete')
  @ApiOperation({ summary: '删除日志' })
  @ApiResponse({ status: 200, description: '操作成功' })
  async delete(
    @Query('ids') query: string,
    @Headers() headers,
  ): Promise<IResponseData> {
    const res = await this.logService.delete(query);
    return responseData({
      code: 100040,
      data: res,
      language: headers['language'],
    });
  }

  @Delete('clear')
  @IsAuth('system:log:clear')
  @ApiOperation({ summary: '清空日志' })
  @ApiResponse({ status: 200, description: '操作成功' })
  async clear(@Headers() headers): Promise<IResponseData> {
    await this.logService.clear();
    return responseData({
      code: 0,
      language: headers['language'],
    });
  }
}
